#include "BaseObject.h"
#include "../SGD Wrappers/SGD_GraphicsManager.h"
#include <cassert>
#include "ParticleSystem.h"
#include "GameplayState.h"
#include "Game.h"
#include "Camera.h"


BaseObject::BaseObject() :Listener(this)
{
	m_vtRectPoints = new std::vector<SGD::Point>;
	//m_vtRectPoints->resize(4);
}

BaseObject::~BaseObject()
{
	//SGD::GraphicsManager::GetInstance()->UnloadTexture(m_hImage);
	
	for (unsigned int i = 0; i < m_vtParticle.size(); i++)
	{
		delete m_vtParticle[i];
	}

	m_vtParticle.clear();

	m_vtRectPoints->clear();
		delete m_vtRectPoints;
}
void BaseObject::Update(float dt)
{
	if (m_vtParticle.size() > 0)
		m_vtParticle[0]->Update(dt);
}

void BaseObject::Render()
{
	// Verify the image
	assert(m_hImage != SGD::INVALID_HANDLE && "BaseObject::Render - image was not set!");

	// Draw the image
	if (GetAlive())
	SGD::GraphicsManager::GetInstance()->DrawTexture(
		m_hImage, m_ptPosition,
		m_fRotation, m_szSize / 2);



}

SGD::Rectangle BaseObject::GetRect() const
{
	//return SGD::Rectangle{ m_ptPosition, m_szSize };
	
	SGD::Point camera = { m_ptPosition.x, m_ptPosition.y };

	SGD::Rectangle rect { camera, m_szSize };


	
	return rect;
}

void BaseObject::HandleCollision( BaseObject* pOther)
{

}

void BaseObject::SetParticle(ParticleSystem particle)
{	
	particle.GetEmitter()->GetFlyweight()->AddRef();
	ParticleSystem* temp = new ParticleSystem(particle);
	temp->GetEmitter()->GetFlyweight()->AddRef();
	m_vtParticle.push_back(temp);
}

void BaseObject::AddRef()
{
	assert(m_unRefCount != 0xFFFFFFFF && "Entity::AddRef - maximum reference count has been exceeded");

	++m_unRefCount;
}

void BaseObject::Release()
{
	--m_unRefCount;

	if (m_unRefCount == 0)
		delete this;
}

void BaseObject::SetRectPoints(float angle)
{
	SGD::Rectangle rect ={ m_ptPosition, m_szSize };

	m_vtRectPoints->push_back({rect.left, rect.top}); // 0
	m_vtRectPoints->push_back({ rect.right, rect.top }); // 1
	m_vtRectPoints->push_back({ rect.right, rect.bottom }); // 2
	m_vtRectPoints->push_back({ rect.left, rect.bottom });  //3

	if (angle != 0)
	{
		for (unsigned char i = 0; i < m_vtRectPoints->size(); i++)
		{
			float x = m_vtRectPoints->at(i).x*cos(angle) - m_vtRectPoints->at(i).y*sin(angle);
			float y = m_vtRectPoints->at(i).x*sin(angle) + m_vtRectPoints->at(i).y*cos(angle);

			m_vtRectPoints->at(i).x = x;
			m_vtRectPoints->at(i).y = y;
		}
	}
}